import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const billStore = createSlice({
  name: "billStore",
  initialState: {
    billList: [],
  },
  reducers: {
    setBill: (state, action) => {
      state.billList = action.payload;
    },
    addBill: (state, action) => {
      state.billList.push(action.payload);
    },
    deleteBill: (state, action) => {
      state.billList = state.billList.filter((item) => item.id !== action.payload);
    },
    updateBill: (state, action) => {
      state.billList = state.billList.map((item) => {
        if (item.id === action.payload.id) {
          return action.payload;
        }
        return item;
      });
    },
  },
})

const { setBill, addBill } = billStore.actions
const getBillList = () => {
    // console.log("getBillList");
    return async (dispatch) => {
        const res = await axios.get('http://localhost:3333/ka')
        dispatch(setBill(res.data))
    }
}
const addBillList = (data) => {
    return async (dispatch) => {
        const res = await axios.post('http://localhost:3333/ka', data)
        dispatch(addBill(res.data))
    }
}
export { setBill, getBillList,addBillList }

const reducer = billStore.reducer
export default reducer// exportamos el reducer y la acción setBill